package com.javaee.wordtree.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaee.wordtree.entity.MessageWithRagInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * RAG信息处理工具类
 */
@Component
@Slf4j
public class RagInfoUtil {

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将RAG结果列表转换为JSON字符串
     * 
     * @param ragResults RAG结果列表
     * @return JSON字符串
     */
    public String ragResultsToJson(List<MessageWithRagInfo.RagResultSummary> ragResults) {
        try {
            return objectMapper.writeValueAsString(ragResults);
        } catch (JsonProcessingException e) {
            log.error("转换RAG结果为JSON时发生错误", e);
            return null;
        }
    }

    /**
     * 将JSON字符串转换为RAG结果列表
     * 
     * @param jsonString JSON字符串
     * @return RAG结果列表
     */
    public List<MessageWithRagInfo.RagResultSummary> jsonToRagResults(String jsonString) {
        try {
            if (jsonString == null || jsonString.trim().isEmpty()) {
                return null;
            }
            return objectMapper.readValue(jsonString,
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class, MessageWithRagInfo.RagResultSummary.class));
        } catch (JsonProcessingException e) {
            log.error("解析RAG结果JSON时发生错误: {}", jsonString, e);
            return null;
        }
    }

    /**
     * 将RAG增强信息转换为JSON字符串
     * 
     * @param ragInfo RAG增强信息
     * @return JSON字符串
     */
    public String ragInfoToJson(MessageWithRagInfo.RagEnhancementInfo ragInfo) {
        try {
            return objectMapper.writeValueAsString(ragInfo);
        } catch (JsonProcessingException e) {
            log.error("转换RAG增强信息为JSON时发生错误", e);
            return null;
        }
    }

    /**
     * 将JSON字符串转换为RAG增强信息
     * 
     * @param jsonString JSON字符串
     * @return RAG增强信息
     */
    public MessageWithRagInfo.RagEnhancementInfo jsonToRagInfo(String jsonString) {
        try {
            if (jsonString == null || jsonString.trim().isEmpty()) {
                return null;
            }
            return objectMapper.readValue(jsonString, MessageWithRagInfo.RagEnhancementInfo.class);
        } catch (JsonProcessingException e) {
            log.error("解析RAG增强信息JSON时发生错误: {}", jsonString, e);
            return null;
        }
    }
}
